<?php

namespace app\admin\controller\admin;

use app\common\controller\AdminController;
use app\common\services\annotation\ControllerAnnotation;
use app\common\services\annotation\NodeAnnotation;
use app\common\services\tool\CommonTool;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use support\Request;
use support\Response;
use think\Exception;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="channel_activity")
 */
class ChannelActivityController extends AdminController
{

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\ChannelActivity();
    }

    /**
     * @NodeAnnotation(title="列表")
     */
    public function index(Request $request): Response
    {
        $channel_id = $request->get('channel_id');
        if (!$request->isAjax()) {
            return $this->fetch('', ['channelId' => $channel_id]);
        }
        list($page, $limit) = $this->buildTableParams();
        $count = $this->model
            ->alias('a')
            ->field("a.id, b.activity_title")
            ->join('activity b', 'b.id=a.activity_id', 'left')
            ->count();
        $list  = $this->model
            ->alias('a')
            ->field("a.id, b.activity_title")
            ->join('activity b', 'b.id=a.activity_id', 'left')
            ->order($this->order)->page($page, $limit)->select()->toArray();
        $data  = [
            'code'  => 0,
            'msg'   => '',
            'count' => $count,
            'data'  => $list,
        ];
        return json($data);
    }

    /**
     * @NodeAnnotation(title="添加")
     */
    public function add(Request $request): Response
    {
        if ($request->isAjax()) {
            $post = $request->post();
            try {
                // 盲盒活动
                preg_match_all('/\[(.*?)\]/', $post['activity_id'], $matches);
                $post['activity_id'] = $matches[1][0];
                $post['channel_id'] = $request->get('channel_id');
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                return $this->error('保存失败:' . $e->getMessage());
            }
            return $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }

    /**
     * @NodeAnnotation(title="编辑")
     */
    public function edit(Request $request)
    {
        $id  = (int)$request->input('id');
        $row = $this->model->find($id);
        // 活动
        $row['activity_id'] = '['.$row['activity_id'].'] '.Db::name('activity')->where(['id' => $row['activity_id']])->value('name');
        if (empty($row)) return $this->error('数据不存在');
        if ($request->isAjax()) {
            $post = $request->post();
            try {
                // 活动
                preg_match_all('/\[(.*?)\]/', $post['activity_id'], $matches);
                $post['activity_id'] = $matches[1][0];
                $post['channel_id'] = $request->get('channel_id');
                $save = $row->save($post);
            } catch (\PDOException|\Exception $e) {
                return $this->error('保存失败:' . $e->getMessage());
            }
            return $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign(compact('row'));
        return $this->fetch();
    }

    /**
     * @NodeAnnotation(title="删除")
     */
    public function delete(Request $request): Response
    {
        if (!$request->isAjax()) return $this->error();
        $id = $request->input('id');
        if (!is_array($id)) $id = (array)$id;
        $row = $this->model->whereIn('id', $id)->field('id')->select()->toArray();
        if (empty($row)) return $this->error('数据不存在');
        try {
            $save = $this->model->whereIn('id', $id)->delete();
        } catch (\PDOException|\Exception $e) {
            return $this->error('删除失败:' . $e->getMessage());
        }
        return $save ? $this->success('删除成功') : $this->error('删除失败');
    }
}
